package com.it.controller;
import com.it.common.Result;
import com.it.domain.Article;
import com.it.domain.User;
import com.it.service.ArticleService;
import com.it.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/article")
@RestController
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private LoginService loginService;



    @PostMapping("/AddArticle")
    public Object AddArticle(@RequestBody Article article, HttpServletRequest request){

        String title = article.getTitle().trim();
        String content = article.getContent().trim();
        String descr = article.getDescr();

        if(title == null || title == "" || content == null || content == "" || descr == null || descr ==""){
            return Result.fail("404","内容为空");

        }
        String token = request.getHeader("token");
        User user = loginService.CheckToken(token);
        if(user == null){
            return Result.fail("404","登录过期");
        }

        article.setAuthorId(user.getId());
        article.setStatus((byte) 0);
        article.setUpdateTime(article.getCreateTime());

        System.out.println(article.toString());

        if(articleService.AddArticle(article)){
            return Result.success("200","发布成功");
        }
        return Result.fail("606","发布失败");
    }

    @GetMapping("/GetAll")
    public List<Article> GetAll(){
        List<Article> articleList = articleService.GetAll();
        System.out.println(articleList);
        return articleList;
    }


    @GetMapping("/SelectById/{id}")
    public Article SelectById(@PathVariable Integer id){

        return articleService.SelectById(id);
    }

    @GetMapping("/SelectByAuthorId")
    public List<Article> SelectByAuthorId(HttpServletRequest request){
        String token = request.getHeader("token");
        if(token == null){
            return null;
        }
        User user = loginService.CheckToken(token);
        if(user == null){
            return null;
        }
        Integer authorId = user.getId();
        return articleService.SelectByAuthorId(authorId);
    }
}
